import { createRouter, createWebHashHistory } from 'vue-router'
const Index = () => import(/* webpackChunkName: 'IndexHome' */ '../views/home/index.vue')
const Home = () => import(/* webpackChunkName: 'IndexHome' */ '../views/home/Home.vue')

const Login = () => import(/* webpackChunkName: 'LoginRegister' */ '../views/login/Login.vue')
const Register = () => import(/* webpackChunkName: 'ImportFuncDemo' */ '../views/login/Register.vue')

const Shop = () => import(/* webpackChunkName: 'Shop' */ '../views/shop/Shop.vue')
const Cart = () => import(/* webpackChunkName: 'Order' */ '../views/cart/index.vue')
const SureOrder = () => import(/* webpackChunkName: 'Order' */ '../views/sureorder/SureOrder.vue')
const Order = () => import(/* webpackChunkName: 'Order' */ '../views/order/index.vue')

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/index',
    name: 'Index',
    component: Index,
    redirect: '/home',
    children: [
      {
        path: '/home',
        name: Home,
        component: Home
      },
      {
        path: '/cart',
        name: Cart,
        component: Cart
      },
      {
        path: '/order',
        name: Order,
        component: Order
      }
    ]
  },
  {
    path: '/sureorder/:id',
    name: SureOrder,
    component: SureOrder
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    beforeEnter (to, from, next) {
      const { isLogin } = localStorage
      // if (isLogin && to.name === 'Login') next('/')
      // next()
      // 已经登录 再跳转到登录页是不允许的
      isLogin ? next('/') : next()
    }
  }, {
    path: '/register',
    name: 'Register',
    component: Register,
    beforeEnter (to, from, next) {
      const { isLogin } = localStorage
      // if (isLogin && to.name === 'Login') next('/')
      // next()
      // 已经登录 再跳转到登录页是不允许的
      isLogin ? next('/') : next()
    }
  },
  {
    path: '/shop/:id',
    name: 'Shop',
    component: Shop
  }
  // {
  //   path: '/loin',
  //   name: 'Login',
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }.{
  //   path: '/loin',
  //   name: 'Login',
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})
router.beforeEach((to, from, next) => {
  const { isLogin } = localStorage
  const { name } = to
  const isLoginOrRegister = (name === 'Login' || name === 'Register')
  if (isLogin || isLoginOrRegister) {
    next() // 已登录或要去登录 放行
  } else {
    next({ name: 'Login' })
  }
  // 未登录 去登录页
  // if (!isLogin) next({ name: 'Login' })
  // next()
})

export default router
